package com.gradle.factory;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;





import org.reflections.Reflections;



import org.springframework.beans.factory.config.AutowireCapableBeanFactory;

import com.gradle.annotation.Pay;
import com.gradle.service.Strategy;
import com.gradle.util.ContextUtil;

/**
 * 工厂
 * @author Administrator
 *
 */
public class StratrgyFactory {

	private static StratrgyFactory stratrgyFactory = new StratrgyFactory();
	private StratrgyFactory(){}
	
	/**
	 * 保存所有使用@pay注解 使用channelId作为ky,注解标记的类的Class做为value
	 */
	private static Map<Integer,String> classMap = new HashMap<Integer,String>();
	
	// 提供外部访问方法
	public static StratrgyFactory getInstance(){
		return stratrgyFactory;
	}
	
	/**
	 * 获取所有使用@Pay标记的类
	 */
	static{
		Reflections reflections = new Reflections("com.gradle.service.impl");
		Set<Class<?>> clazzs =  reflections.getTypesAnnotatedWith(Pay.class);
		clazzs.forEach(clazz -> {
			Pay pay = clazz.getAnnotation(Pay.class);
			// 保存到map中
			classMap.put(pay.channelId(), clazz.getCanonicalName());
		});
	}
	
	/**
	 * 通过反射根据渠道id获取所需要的实例
	 * @param channelId
	 * @return
	 */
	public Strategy create(Integer channelId){
		try{
			String caszz =  classMap.get(channelId);
			Class<?> cl = Class.forName(caszz);
			// 使用applicationContext实例化对象，不然实例化的类中注入的对象无法获取
			Strategy strategy = (Strategy)ContextUtil.getContext().getAutowireCapableBeanFactory()
							        .createBean(cl, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
			return strategy;
		}catch(Exception e){e.printStackTrace();}
		return null;
	}
}
